<template>
  <view class="home">
    <scroll-view
      scroll-x
      class="categories"
      :scroll-left="scrollLeft"
      scroll-with-animation
    >
      <view
        v-for="(category, index) in categories"
        :key="category.id"
        class="category"
        :class="{ highlighted: selectedIndex === index }"
        @click="selectCategory(index)"
      >
        {{ category.name }}
      </view>
    </scroll-view>
    <view class="topics">
      <topic v-for="(topic, index) in topics" :topic="topic" :key="topic.id" />
    </view>
  </view>
</template>

<script>
import { fetchData, selectFromQuery } from "../../utils";
export default {
  data() {
    return {
      categories: [],
      selectedIndex: 0,
      scrollLeft: 0,
      currentPage: 1,
      pageSize: 10,
      totalPages: 0,
      topics: [],
      isTopicLoading: false, //标识当前是否正在加载文章中
    };
  },
  async onLoad() {
    await this.fetchCategories();
    await this.fetchTopics();
  },
  //当滚动到底部的执行
  onReachBottom() {
    //如果已经在加载中了，则什么都不做
    if (this.isTopicLoading) {
      return;
    }
    //如果不是最后一页，并且不在加载中，则加载下一页的数据
    if (this.currentPage <= this.totalPages) {
      this.fetchTopics();
    } else {
      return uni.showToast({
        title: "没有更多数据了",
        icon: "none",
        duration: 2000,
      });
    }
  },
  async onPullDownRefresh() {
    await this.refreshTopics();
    uni.stopPullDownRefresh(); //当刷新完成后停止刷新动画
  },
  watch: {
    selectedIndex() {
      //观察选中索引的变化，当发生变化后重新请求题目
      this.refreshTopics();
    },
  },
  methods: {
    async refreshTopics() {
      this.topics = [];
      this.currentPage = 1;
      this.totalPages = 0;
      await this.fetchTopics();
    },
    async fetchTopics() {
      if (this.categories.length == 0) {
        return;
      }
      this.isTopicLoading = true;
      uni.showLoading({
        title: "加载中",
      });
      //获取选中的分类的分类ID
      const category_id = this.categories[this.selectedIndex].id;
      try {
        const { list, totalPages } = await fetchData({
          method: "GET",
          url: `/topics`,
          data: {
            category_id,
            currentPage: this.currentPage,
            pageSize: this.pageSize,
          },
        });
        //合并老的和新的数组
        this.topics = [...this.topics, ...list];
        //记录总页数
        this.totalPages = totalPages;
        //让当前页码加1
        this.currentPage++;
      } catch (error) {
        uni.showToast({
          title: error.message,
          icon: "error",
          duration: 2000,
        });
      } finally {
        uni.hideLoading();
        this.isTopicLoading = false;
      }
    },
    async fetchCategories() {
      try {
        this.categories = await fetchData({
          method: "GET",
          url: "/categories",
        });
      } catch (error) {
        uni.showToast({
          title: error.message,
          icon: "error",
          duration: 2000,
        });
      }
    },
    async selectCategory(index) {
      if (index === this.selectedIndex) return;
      this.selectedIndex = index;
      const [[scrollOffset], [boundingClientRect]] = await Promise.all([
        selectFromQuery(".categories", "select", "scrollOffset"),
        selectFromQuery(`.category`, "selectAll", "boundingClientRect"),
      ]);
      //计算滚动容器向左滚动的距离
      //现在容器向左滚动的距离+点击的元素距离 屏幕左侧的距离-屏幕宽度的一半+点击元素宽度的一半
      this.scrollLeft =
        scrollOffset.scrollLeft +
        boundingClientRect[index].left -
        uni.getSystemInfoSync().windowWidth / 2 +
        boundingClientRect[index].width / 2;
    },
  },
};
</script>

<style lang="scss" scoped>
.home {
  .categories {
    position: fixed;
    left: 0;
    top: var(--window-top);
    z-index: 100;
    white-space: nowrap;
    width: 100%;
    height: 100rpx;
    overflow: auto;
    overflow-y: hidden;
    background-color: #f5f5f5;

    /deep/ ::-webkit-scrollbar {
      display: none;
    }

    .category {
      display: inline-block;
      height: 100%;
      overflow: hidden;
      padding: 0 20rpx;
      line-height: 100rpx;
      text-align: center;
      border: 1px solid #c5c5c5;
      box-sizing: border-box;
      &.highlighted {
        color: #1baeae;
        border: 1px dashed #1baeae;
      }
    }
  }
}
.topics {
  padding-top: 100rpx;
}
</style>
